package yartiss.engine.simulation.system.taskset.generation.task;

import java.util.Random;

import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.taskset.generation.ITaskGenerator;

/**
 * AbstractTaskGenerator is an abstract class that implements the ITaskGenerator
 * interface, and generates real-time tasks.
 * 
 * @author Frederic Fauberteau
 */
public abstract class AbstractTaskGenerator implements ITaskGenerator {

	private final static long MAX_PERIOD = 1000;
	private static int CURRENT_PRIORITY = 1;
	protected final Random random = new Random();

	@Override
	public ITask generate(double utilization, double energyUtilization,
			long pr, boolean offset, int deadlineModel, int maxProc) {
		long start = 0;
		long period = nextInt(1, (int) MAX_PERIOD);
		long wcet = Math.max(1, (long) (period * utilization));
		long deadline = period; // implicit deadline
		if (deadlineModel < 0) { // constrained deadline
			deadline = nextInt((int) wcet, (int) period);
		} else if (deadlineModel > 0) { // arbitrary deadline
			deadline = nextInt(1, (int) MAX_PERIOD);
		}
		if (offset) {
			start = nextInt(0, (int) period);
		}
		int priority = CURRENT_PRIORITY++;
		if (CURRENT_PRIORITY > 100)
			CURRENT_PRIORITY = 1;

		return generate(start, wcet, period, deadline, priority, maxProc);
	}

	protected abstract ITask generate(long start, long wcet, long period,
			long deadline, int priority, int maxProc);

	protected int nextInt(int from, int to) {
		return from + random.nextInt(to - from + 1);
	}
}
